<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="如题，多种压缩方式常用的有尺寸压缩、质量压缩以及通过JNI调用libjpeg库来进行压缩，三种方式结合使用实现指定图片内存大小，清晰度达到最优，下面就先分别介绍下这几种压缩方式。  质量压缩设置bitmap options属性，降低图片的质量，像素不会减少，第一个参数为需要压缩的bitmap图片对象，第二个参数为压缩后图片保存的位置，设置options 属性0-100，来实现压缩 public">
<meta name="keywords" content="Android">
<meta property="og:type" content="article">
<meta property="og:title" content="图片压缩之多种压缩方式结合使用">
<meta property="og:url" content="http://soaic.github.io/2016/04/11/2016-04-11-Android/index.html">
<meta property="og:site_name" content="Soaic&#39;s Blog">
<meta property="og:description" content="如题，多种压缩方式常用的有尺寸压缩、质量压缩以及通过JNI调用libjpeg库来进行压缩，三种方式结合使用实现指定图片内存大小，清晰度达到最优，下面就先分别介绍下这几种压缩方式。  质量压缩设置bitmap options属性，降低图片的质量，像素不会减少，第一个参数为需要压缩的bitmap图片对象，第二个参数为压缩后图片保存的位置，设置options 属性0-100，来实现压缩 public">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-08-17T17:34:03.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="图片压缩之多种压缩方式结合使用">
<meta name="twitter:description" content="如题，多种压缩方式常用的有尺寸压缩、质量压缩以及通过JNI调用libjpeg库来进行压缩，三种方式结合使用实现指定图片内存大小，清晰度达到最优，下面就先分别介绍下这几种压缩方式。  质量压缩设置bitmap options属性，降低图片的质量，像素不会减少，第一个参数为需要压缩的bitmap图片对象，第二个参数为压缩后图片保存的位置，设置options 属性0-100，来实现压缩 public">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://soaic.github.io/2016/04/11/2016-04-11-Android/"/>





  <title>图片压缩之多种压缩方式结合使用 | Soaic's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Soaic's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Soaic</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-music">
          <a href="/music/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-music"></i> <br />
            
            音乐
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://soaic.github.io/2016/04/11/2016-04-11-Android/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Soaic">
      <meta itemprop="description" content="Welcome!">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Soaic's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">图片压缩之多种压缩方式结合使用</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-04-11T22:41:00+08:00">
                2016-04-11
              </time>
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2016/04/11/2016-04-11-Android/" class="leancloud_visitors" data-flag-title="图片压缩之多种压缩方式结合使用">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>如题，多种压缩方式常用的有尺寸压缩、质量压缩以及通过JNI调用libjpeg库来进行压缩，三种方式结合使用实现指定图片内存大小，清晰度达到最优，下面就先分别介绍下这几种压缩方式。</p>
</blockquote>
<h3 id="质量压缩"><a href="#质量压缩" class="headerlink" title="质量压缩"></a>质量压缩</h3><p>设置bitmap options属性，降低图片的质量，像素不会减少，第一个参数为需要压缩的bitmap图片对象，第二个参数为压缩后图片保存的位置，设置options 属性0-100，来实现压缩</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">compressImageToFile</span><span class="params">(Bitmap bmp,File file)</span> </span>&#123;</div><div class="line">	<span class="comment">// 0-100 100为不压缩</span></div><div class="line">	<span class="keyword">int</span> options = <span class="number">100</span>; </div><div class="line">	ByteArrayOutputStream baos = <span class="keyword">new</span> ByteArrayOutputStream();</div><div class="line">	<span class="comment">// 把压缩后的数据存放到baos中</span></div><div class="line">	bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);</div><div class="line">	<span class="keyword">try</span> &#123;  </div><div class="line">        FileOutputStream fos = <span class="keyword">new</span> FileOutputStream(file);  </div><div class="line">        fos.write(baos.toByteArray());  </div><div class="line">        fos.flush();  </div><div class="line">        fos.close();  </div><div class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;  </div><div class="line">        e.printStackTrace();  </div><div class="line">    &#125; </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<a id="more"></a>
<h3 id="尺寸压缩"><a href="#尺寸压缩" class="headerlink" title="尺寸压缩"></a>尺寸压缩</h3><p>通过缩放图片像素来减少图片占用内存大小</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">compressBitmapToFile</span><span class="params">(Bitmap bmp, File file)</span></span>&#123;</div><div class="line">	<span class="comment">// 尺寸压缩倍数,值越大，图片尺寸越小</span></div><div class="line">	<span class="keyword">int</span> ratio = <span class="number">2</span>;</div><div class="line">	<span class="comment">// 压缩Bitmap到对应尺寸</span></div><div class="line">	Bitmap result = Bitmap.createBitmap(bmp.getWidth() / ratio, bmp.getHeight() / ratio, Config.ARGB_8888);</div><div class="line">	Canvas canvas = <span class="keyword">new</span> Canvas(result);</div><div class="line">	Rect rect = <span class="keyword">new</span> Rect(<span class="number">0</span>, <span class="number">0</span>, bmp.getWidth() / ratio, bmp.getHeight() / ratio);</div><div class="line">	canvas.drawBitmap(bmp, <span class="keyword">null</span>, rect, <span class="keyword">null</span>);</div><div class="line">	</div><div class="line">	ByteArrayOutputStream baos = <span class="keyword">new</span> ByteArrayOutputStream();</div><div class="line">	<span class="comment">// 把压缩后的数据存放到baos中</span></div><div class="line">	result.compress(Bitmap.CompressFormat.JPEG, <span class="number">100</span> ,baos);</div><div class="line">	<span class="keyword">try</span> &#123;  </div><div class="line">        FileOutputStream fos = <span class="keyword">new</span> FileOutputStream(file);  </div><div class="line">        fos.write(baos.toByteArray());  </div><div class="line">        fos.flush();  </div><div class="line">        fos.close();  </div><div class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;  </div><div class="line">        e.printStackTrace();  </div><div class="line">    &#125; </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>设置图片的采样率，降低图片像素</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">compressBitmap</span><span class="params">(String filePath, File file)</span></span>&#123;</div><div class="line">	<span class="comment">// 数值越高，图片像素越低</span></div><div class="line">	<span class="keyword">int</span> inSampleSize = <span class="number">2</span>;</div><div class="line">	BitmapFactory.Options options = <span class="keyword">new</span> BitmapFactory.Options();</div><div class="line">	<span class="comment">//采样率</span></div><div class="line">	options.inSampleSize = inSampleSize;</div><div class="line">	Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);  </div><div class="line">	</div><div class="line">	ByteArrayOutputStream baos = <span class="keyword">new</span> ByteArrayOutputStream();</div><div class="line">	<span class="comment">// 把压缩后的数据存放到baos中</span></div><div class="line">	bitmap.compress(Bitmap.CompressFormat.JPEG, <span class="number">100</span> ,baos);</div><div class="line">	<span class="keyword">try</span> &#123;  </div><div class="line">        FileOutputStream fos = <span class="keyword">new</span> FileOutputStream(file);  </div><div class="line">        fos.write(baos.toByteArray());  </div><div class="line">        fos.flush();  </div><div class="line">        fos.close();  </div><div class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;  </div><div class="line">        e.printStackTrace();  </div><div class="line">    &#125; </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="JNI调用libjpeg库压缩"><a href="#JNI调用libjpeg库压缩" class="headerlink" title="JNI调用libjpeg库压缩"></a>JNI调用libjpeg库压缩</h3><blockquote>
<p>JNI静态调用 bitherlibjni.c 中的方法来实现压缩</p>
</blockquote>
<p><code>Java_net_bither_util_NativeUtil_compressBitmap</code><br><code>net_bither_util</code>为包名，<code>NativeUtil</code>为类名，<code>compressBitmap</code>为<code>native</code>方法名，后面我会把整个类分享出来</p>
<p>我们只需要调用<code>saveBitmap()</code>方法就可以，bmp 需要压缩的Bitmap对象, quality压缩质量0-100, fileName 压缩后要保存的文件地址, optimize 是否采用哈弗曼表数据计算 品质相差5-10倍</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><div class="line"><span class="function">jstring <span class="title">Java_net_bither_util_NativeUtil_compressBitmap</span><span class="params">(JNIEnv* env,</span></span></div><div class="line"><span class="function"><span class="params">	jobject thiz, jobject bitmapcolor, <span class="keyword">int</span> w, <span class="keyword">int</span> h, <span class="keyword">int</span> quality,</span></span></div><div class="line"><span class="function"><span class="params">	jbyteArray fileNameStr, jboolean optimize)</span> </span>&#123;</div><div class="line"></div><div class="line">AndroidBitmapInfo infocolor;</div><div class="line">BYTE* pixelscolor;</div><div class="line"><span class="keyword">int</span> ret;</div><div class="line">BYTE * data;</div><div class="line">BYTE *tmpdata;</div><div class="line"><span class="keyword">char</span> * fileName = jstrinTostring(env, fileNameStr);</div><div class="line"><span class="keyword">if</span> ((ret = AndroidBitmap_getInfo(env, bitmapcolor, &amp;infocolor)) &lt; <span class="number">0</span>) &#123;</div><div class="line">	LOGE(<span class="string">"AndroidBitmap_getInfo() failed ! error=%d"</span>, ret);</div><div class="line">	<span class="keyword">return</span> (*env)-&gt;NewStringUTF(env, <span class="string">"0"</span>);;</div><div class="line">&#125;</div><div class="line"><span class="keyword">if</span> ((ret = AndroidBitmap_lockPixels(env, bitmapcolor, &amp;pixelscolor)) &lt; <span class="number">0</span>) &#123;</div><div class="line">	LOGE(<span class="string">"AndroidBitmap_lockPixels() failed ! error=%d"</span>, ret);</div><div class="line">&#125;</div><div class="line"></div><div class="line">BYTE r, g, b;</div><div class="line">data = <span class="literal">NULL</span>;</div><div class="line">data = <span class="built_in">malloc</span>(w * h * <span class="number">3</span>);</div><div class="line">tmpdata = data;</div><div class="line"><span class="keyword">int</span> j = <span class="number">0</span>, i = <span class="number">0</span>;</div><div class="line"><span class="keyword">int</span> color;</div><div class="line"><span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; h; i++) &#123;</div><div class="line">	<span class="keyword">for</span> (j = <span class="number">0</span>; j &lt; w; j++) &#123;</div><div class="line">		color = *((<span class="keyword">int</span> *) pixelscolor);</div><div class="line">		r = ((color &amp; <span class="number">0x00FF0000</span>) &gt;&gt; <span class="number">16</span>);</div><div class="line">		g = ((color &amp; <span class="number">0x0000FF00</span>) &gt;&gt; <span class="number">8</span>);</div><div class="line">		b = color &amp; <span class="number">0x000000FF</span>;</div><div class="line">		*data = b;</div><div class="line">		*(data + <span class="number">1</span>) = g;</div><div class="line">		*(data + <span class="number">2</span>) = r;</div><div class="line">		data = data + <span class="number">3</span>;</div><div class="line">		pixelscolor += <span class="number">4</span>;</div><div class="line"></div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div><div class="line">AndroidBitmap_unlockPixels(env, bitmapcolor);</div><div class="line"><span class="keyword">int</span> resultCode= generateJPEG(tmpdata, w, h, quality, fileName, optimize);</div><div class="line"><span class="built_in">free</span>(tmpdata);</div><div class="line"><span class="keyword">if</span>(resultCode==<span class="number">0</span>)&#123;</div><div class="line">	jstring result=(*env)-&gt;NewStringUTF(env, error);</div><div class="line">	error=<span class="literal">NULL</span>;</div><div class="line">	<span class="keyword">return</span> result;</div><div class="line">&#125;</div><div class="line"><span class="keyword">return</span> (*env)-&gt;NewStringUTF(env, <span class="string">"1"</span>); <span class="comment">//success</span></div><div class="line">&#125;</div><div class="line"></div><div class="line">compressBitmap()为native关联方法，saveBitmap() 压缩调用方法</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> native String <span class="title">compressBitmap</span><span class="params">(Bitmap bit, <span class="keyword">int</span> w, <span class="keyword">int</span> h, <span class="keyword">int</span> quality, byte[] fileNameBytes,</span></span></div><div class="line"><span class="function"><span class="params">		boolean optimize)</span></span>;</div><div class="line">		</div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">saveBitmap</span><span class="params">(Bitmap bmp, <span class="keyword">int</span> quality, String fileName, boolean optimize)</span> </span>&#123;</div><div class="line">	compressBitmap(bit, bit.getWidth(), bit.getHeight(), quality, fileName.getBytes(), optimize);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="结合三种方式的终极压缩"><a href="#结合三种方式的终极压缩" class="headerlink" title="结合三种方式的终极压缩"></a>结合三种方式的终极压缩</h3><blockquote>
<p>首先通过尺寸压缩，压缩到手机常用的一个分辨率(1280*960 微信好像是压缩到这个分辨率),然后我们要把图片压缩到100KB以内，通过质量压缩来计算options需要设置为多少，最后调用JNI压缩，这边我测试了下，压缩出来的清晰度和原图几乎差不多，压缩时间大概1秒钟左右</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">getRatioSize</span><span class="params">(<span class="keyword">int</span> bitWidth, <span class="keyword">int</span> bitHeight)</span> </span>&#123;</div><div class="line">	<span class="comment">// 图片最大分辨率</span></div><div class="line">	<span class="keyword">int</span> imageHeight = <span class="number">1280</span>;</div><div class="line">	<span class="keyword">int</span> imageWidth = <span class="number">960</span>;</div><div class="line">	<span class="comment">// 缩放比</span></div><div class="line">	<span class="keyword">int</span> ratio = <span class="number">1</span>;</div><div class="line">	<span class="comment">// 缩放比,由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可</span></div><div class="line">	<span class="keyword">if</span> (bitWidth &gt; bitHeight &amp;&amp; bitWidth &gt; imageWidth) &#123;</div><div class="line">		<span class="comment">// 如果图片宽度比高度大,以宽度为基准</span></div><div class="line">		ratio = bitWidth / imageWidth;</div><div class="line">	&#125; <span class="keyword">else</span> <span class="keyword">if</span> (bitWidth &lt; bitHeight &amp;&amp; bitHeight &gt; imageHeight) &#123;</div><div class="line">		<span class="comment">// 如果图片高度比宽度大，以高度为基准</span></div><div class="line">		ratio = bitHeight / imageHeight;</div><div class="line">	&#125;</div><div class="line">	<span class="comment">// 最小比率为1</span></div><div class="line">	<span class="keyword">if</span> (ratio &lt;= <span class="number">0</span>)</div><div class="line">		ratio = <span class="number">1</span>;</div><div class="line">	<span class="keyword">return</span> ratio;</div><div class="line">&#125;</div><div class="line">	</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">compressBitmap</span><span class="params">(Bitmap image, String filePath)</span> </span>&#123;</div><div class="line">	<span class="comment">// 最大图片大小 100KB</span></div><div class="line">	<span class="keyword">int</span> maxSize = <span class="number">100</span>;</div><div class="line">	<span class="comment">// 获取尺寸压缩倍数</span></div><div class="line">	<span class="keyword">int</span> ratio = NativeUtil.getRatioSize(image.getWidth(), image.getHeight());</div><div class="line">	<span class="comment">// 压缩Bitmap到对应尺寸</span></div><div class="line">	Bitmap result = Bitmap.createBitmap(image.getWidth() / ratio, image.getHeight() / ratio, Config.ARGB_8888);</div><div class="line">	Canvas canvas = <span class="keyword">new</span> Canvas(result);</div><div class="line">	Rect rect = <span class="keyword">new</span> Rect(<span class="number">0</span>, <span class="number">0</span>, image.getWidth() / ratio, image.getHeight() / ratio);</div><div class="line">	canvas.drawBitmap(image, <span class="keyword">null</span>, rect, <span class="keyword">null</span>);</div><div class="line"></div><div class="line">	ByteArrayOutputStream baos = <span class="keyword">new</span> ByteArrayOutputStream();</div><div class="line">	<span class="comment">// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中</span></div><div class="line">	<span class="keyword">int</span> options = <span class="number">100</span>;</div><div class="line">	result.compress(Bitmap.CompressFormat.JPEG, options, baos);</div><div class="line">	<span class="comment">// 循环判断如果压缩后图片是否大于100kb,大于继续压缩</span></div><div class="line">	<span class="keyword">while</span> (baos.toByteArray().length / <span class="number">1024</span> &gt; maxSize) &#123;</div><div class="line">		<span class="comment">// 重置baos即清空baos</span></div><div class="line">		baos.reset();</div><div class="line">		<span class="comment">// 每次都减少10</span></div><div class="line">		options -= <span class="number">10</span>;</div><div class="line">		<span class="comment">// 这里压缩options%，把压缩后的数据存放到baos中</span></div><div class="line">		result.compress(Bitmap.CompressFormat.JPEG, options, baos);</div><div class="line">	&#125;</div><div class="line">	<span class="comment">// JNI调用保存图片到SD卡 这个关键</span></div><div class="line">	NativeUtil.saveBitmap(result, options, filePath, <span class="keyword">true</span>);</div><div class="line">	<span class="comment">// 释放Bitmap</span></div><div class="line">	<span class="keyword">if</span> (result != <span class="keyword">null</span> &amp;&amp; !result.isRecycled()) &#123;</div><div class="line">		result.recycle();</div><div class="line">		result = <span class="keyword">null</span>;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="NativeUtil类的源码"><a href="#NativeUtil类的源码" class="headerlink" title="NativeUtil类的源码"></a>NativeUtil类的源码</h3><p><strong><em>16.9.29更新</em></strong><br>1、添加getBitmapFromFile()方法，解决OOM和图片旋转的问题<br>2、添加compressBitmap()方法，传递当前图片本地路径和解压后图片保存路径两个参数，即可，实现压缩</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">package</span> net.bither.util;</div><div class="line"></div><div class="line"><span class="keyword">import</span> java.io.ByteArrayOutputStream;</div><div class="line"><span class="keyword">import</span> java.io.File;</div><div class="line"><span class="keyword">import</span> java.io.FileInputStream;</div><div class="line"><span class="keyword">import</span> java.io.FileNotFoundException;</div><div class="line"><span class="keyword">import</span> java.io.IOException;</div><div class="line"></div><div class="line"><span class="keyword">import</span> android.graphics.Bitmap;</div><div class="line"><span class="keyword">import</span> android.graphics.Bitmap.Config;</div><div class="line"><span class="keyword">import</span> android.graphics.BitmapFactory;</div><div class="line"><span class="keyword">import</span> android.graphics.Canvas;</div><div class="line"><span class="keyword">import</span> android.graphics.Matrix;</div><div class="line"><span class="keyword">import</span> android.graphics.Rect;</div><div class="line"><span class="keyword">import</span> android.media.ExifInterface;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * JNI图片压缩工具类</span></div><div class="line"><span class="comment"> * </span></div><div class="line"><span class="comment"> * <span class="doctag">@Description</span> TODO</span></div><div class="line"><span class="comment"> * <span class="doctag">@Package</span> net.bither.util</span></div><div class="line"><span class="comment"> * <span class="doctag">@Class</span> NativeUtil</span></div><div class="line"><span class="comment"> * <span class="doctag">@Copyright</span>: Copyright (c) 2015</span></div><div class="line"><span class="comment"> * <span class="doctag">@author</span> XiaoSai</span></div><div class="line"><span class="comment"> * <span class="doctag">@date</span> 2016年3月21日 下午2:13:55</span></div><div class="line"><span class="comment"> * <span class="doctag">@version</span> V1.0.0</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NativeUtil</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> DEFAULT_QUALITY = <span class="number">95</span>;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * <span class="doctag">@Description</span>: JNI基本压缩</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> bit</span></div><div class="line"><span class="comment">     *            bitmap对象</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> fileName</span></div><div class="line"><span class="comment">     *            指定保存目录名</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> optimize</span></div><div class="line"><span class="comment">     *            是否采用哈弗曼表数据计算 品质相差5-10倍</span></div><div class="line"><span class="comment">     * <span class="doctag">@author</span> XiaoSai</span></div><div class="line"><span class="comment">     * <span class="doctag">@date</span> 2016年3月23日 下午6:32:49</span></div><div class="line"><span class="comment">     * <span class="doctag">@version</span> V1.0.0</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">compressBitmap</span><span class="params">(Bitmap bit, String fileName, <span class="keyword">boolean</span> optimize)</span> </span>&#123;</div><div class="line">        saveBitmap(bit, DEFAULT_QUALITY, fileName, optimize);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * <span class="doctag">@Description</span>: 通过JNI图片压缩把Bitmap保存到指定目录</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> image</span></div><div class="line"><span class="comment">     *            bitmap对象</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> filePath</span></div><div class="line"><span class="comment">     *            要保存的指定目录</span></div><div class="line"><span class="comment">     * <span class="doctag">@author</span> XiaoSai</span></div><div class="line"><span class="comment">     * <span class="doctag">@date</span> 2016年3月23日 下午6:28:15</span></div><div class="line"><span class="comment">     * <span class="doctag">@version</span> V1.0.0</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">compressBitmap</span><span class="params">(Bitmap image, String filePath)</span> </span>&#123;</div><div class="line">        <span class="comment">// 最大图片大小 150KB</span></div><div class="line">        <span class="keyword">int</span> maxSize = <span class="number">150</span>;</div><div class="line">        <span class="comment">// 获取尺寸压缩倍数</span></div><div class="line">        <span class="keyword">int</span> ratio = NativeUtil.getRatioSize(image.getWidth(),image.getHeight());</div><div class="line">        <span class="comment">// 压缩Bitmap到对应尺寸</span></div><div class="line">        Bitmap result = Bitmap.createBitmap(image.getWidth() / ratio,image.getHeight() / ratio,Config.ARGB_8888);</div><div class="line">        Canvas canvas = <span class="keyword">new</span> Canvas(result);</div><div class="line">        Rect rect = <span class="keyword">new</span> Rect(<span class="number">0</span>, <span class="number">0</span>, image.getWidth() / ratio, image.getHeight() / ratio);</div><div class="line">        canvas.drawBitmap(image,<span class="keyword">null</span>,rect,<span class="keyword">null</span>);</div><div class="line">        ByteArrayOutputStream baos = <span class="keyword">new</span> ByteArrayOutputStream();</div><div class="line">        <span class="comment">// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中</span></div><div class="line">        <span class="keyword">int</span> options = <span class="number">100</span>;</div><div class="line">        result.compress(Bitmap.CompressFormat.JPEG, options, baos);</div><div class="line">        <span class="comment">// 循环判断如果压缩后图片是否大于100kb,大于继续压缩</span></div><div class="line">        <span class="keyword">while</span> (baos.toByteArray().length / <span class="number">1024</span> &gt; maxSize) &#123;</div><div class="line">            <span class="comment">// 重置baos即清空baos</span></div><div class="line">            baos.reset();</div><div class="line">            <span class="comment">// 每次都减少10</span></div><div class="line">            options -= <span class="number">10</span>;</div><div class="line">            <span class="comment">// 这里压缩options%，把压缩后的数据存放到baos中</span></div><div class="line">            result.compress(Bitmap.CompressFormat.JPEG, options, baos);</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// JNI保存图片到SD卡 这个关键</span></div><div class="line">        NativeUtil.saveBitmap(result, options, filePath, <span class="keyword">true</span>);</div><div class="line">        <span class="comment">// 释放Bitmap</span></div><div class="line">        <span class="keyword">if</span> (!result.isRecycled()) &#123;</div><div class="line">            result.recycle();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * <span class="doctag">@Description</span>: 通过JNI图片压缩把Bitmap保存到指定目录</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> curFilePath</span></div><div class="line"><span class="comment">     *            当前图片文件地址</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> targetFilePath</span></div><div class="line"><span class="comment">     *            要保存的图片文件地址</span></div><div class="line"><span class="comment">     * <span class="doctag">@author</span> XiaoSai</span></div><div class="line"><span class="comment">     * <span class="doctag">@date</span> 2016年9月28日 下午17:43:15</span></div><div class="line"><span class="comment">     * <span class="doctag">@version</span> V1.0.0</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">compressBitmap</span><span class="params">(String curFilePath, String targetFilePath)</span> </span>&#123;</div><div class="line">        <span class="comment">// 最大图片大小 150KB</span></div><div class="line">        <span class="keyword">int</span> maxSize = <span class="number">150</span>;</div><div class="line">        <span class="comment">//根据地址获取bitmap</span></div><div class="line">        Bitmap result = getBitmapFromFile(curFilePath);</div><div class="line">        ByteArrayOutputStream baos = <span class="keyword">new</span> ByteArrayOutputStream();</div><div class="line">        <span class="comment">// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中</span></div><div class="line">        <span class="keyword">int</span> quality = <span class="number">100</span>;</div><div class="line">        result.compress(Bitmap.CompressFormat.JPEG, quality, baos);</div><div class="line">        <span class="comment">// 循环判断如果压缩后图片是否大于100kb,大于继续压缩</span></div><div class="line">        <span class="keyword">while</span> (baos.toByteArray().length / <span class="number">1024</span> &gt; maxSize) &#123;</div><div class="line">            <span class="comment">// 重置baos即清空baos</span></div><div class="line">            baos.reset();</div><div class="line">            <span class="comment">// 每次都减少10</span></div><div class="line">            quality -= <span class="number">10</span>;</div><div class="line">            <span class="comment">// 这里压缩quality，把压缩后的数据存放到baos中</span></div><div class="line">            result.compress(Bitmap.CompressFormat.JPEG, quality, baos);</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// JNI保存图片到SD卡 这个关键</span></div><div class="line">        NativeUtil.saveBitmap(result, quality, targetFilePath, <span class="keyword">true</span>);</div><div class="line">        <span class="comment">// 释放Bitmap</span></div><div class="line">        <span class="keyword">if</span> (!result.isRecycled()) &#123;</div><div class="line">            result.recycle();</div><div class="line">        &#125;</div><div class="line">        </div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 计算缩放比</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> bitWidth 当前图片宽度</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> bitHeight 当前图片高度</span></div><div class="line"><span class="comment">     * <span class="doctag">@return</span> int 缩放比</span></div><div class="line"><span class="comment">     * <span class="doctag">@author</span> XiaoSai</span></div><div class="line"><span class="comment">     * <span class="doctag">@date</span> 2016年3月21日 下午3:03:38</span></div><div class="line"><span class="comment">     * <span class="doctag">@version</span> V1.0.0</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">getRatioSize</span><span class="params">(<span class="keyword">int</span> bitWidth, <span class="keyword">int</span> bitHeight)</span> </span>&#123;</div><div class="line">        <span class="comment">// 图片最大分辨率</span></div><div class="line">        <span class="keyword">int</span> imageHeight = <span class="number">1280</span>;</div><div class="line">        <span class="keyword">int</span> imageWidth = <span class="number">960</span>;</div><div class="line">        <span class="comment">// 缩放比</span></div><div class="line">        <span class="keyword">int</span> ratio = <span class="number">1</span>;</div><div class="line">        <span class="comment">// 缩放比,由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可</span></div><div class="line">        <span class="keyword">if</span> (bitWidth &gt; bitHeight &amp;&amp; bitWidth &gt; imageWidth) &#123;</div><div class="line">            <span class="comment">// 如果图片宽度比高度大,以宽度为基准</span></div><div class="line">            ratio = bitWidth / imageWidth;</div><div class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (bitWidth &lt; bitHeight &amp;&amp; bitHeight &gt; imageHeight) &#123;</div><div class="line">            <span class="comment">// 如果图片高度比宽度大，以高度为基准</span></div><div class="line">            ratio = bitHeight / imageHeight;</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// 最小比率为1</span></div><div class="line">        <span class="keyword">if</span> (ratio &lt;= <span class="number">0</span>)</div><div class="line">            ratio = <span class="number">1</span>;</div><div class="line">        <span class="keyword">return</span> ratio;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 通过文件路径读获取Bitmap防止OOM以及解决图片旋转问题</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> filePath</span></div><div class="line"><span class="comment">     * <span class="doctag">@return</span></span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Bitmap <span class="title">getBitmapFromFile</span><span class="params">(String filePath)</span></span>&#123;</div><div class="line">        BitmapFactory.Options newOpts = <span class="keyword">new</span> BitmapFactory.Options();</div><div class="line">        newOpts.inJustDecodeBounds = <span class="keyword">true</span>;<span class="comment">//只读边,不读内容  </span></div><div class="line">        BitmapFactory.decodeFile(filePath, newOpts);</div><div class="line">        <span class="keyword">int</span> w = newOpts.outWidth;</div><div class="line">        <span class="keyword">int</span> h = newOpts.outHeight;</div><div class="line">        <span class="comment">// 获取尺寸压缩倍数</span></div><div class="line">        newOpts.inSampleSize = NativeUtil.getRatioSize(w,h);</div><div class="line">        newOpts.inJustDecodeBounds = <span class="keyword">false</span>;<span class="comment">//读取所有内容</span></div><div class="line">        newOpts.inDither = <span class="keyword">false</span>;</div><div class="line">        newOpts.inPurgeable=<span class="keyword">true</span>;</div><div class="line">        newOpts.inInputShareable=<span class="keyword">true</span>;</div><div class="line">        newOpts.inTempStorage = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">32</span> * <span class="number">1024</span>];</div><div class="line">        Bitmap bitmap = <span class="keyword">null</span>;</div><div class="line">        File file = <span class="keyword">new</span> File(filePath);</div><div class="line">        FileInputStream fs = <span class="keyword">null</span>;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            fs = <span class="keyword">new</span> FileInputStream(file);</div><div class="line">        &#125; <span class="keyword">catch</span> (FileNotFoundException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            <span class="keyword">if</span>(fs!=<span class="keyword">null</span>)&#123;</div><div class="line">                bitmap = BitmapFactory.decodeFileDescriptor(fs.getFD(),<span class="keyword">null</span>,newOpts);</div><div class="line">                <span class="comment">//旋转图片</span></div><div class="line">                <span class="keyword">int</span> photoDegree = readPictureDegree(filePath);</div><div class="line">                <span class="keyword">if</span>(photoDegree != <span class="number">0</span>)&#123;</div><div class="line">                    Matrix matrix = <span class="keyword">new</span> Matrix();</div><div class="line">                    matrix.postRotate(photoDegree);</div><div class="line">                    <span class="comment">// 创建新的图片</span></div><div class="line">                    bitmap = Bitmap.createBitmap(bitmap, <span class="number">0</span>, <span class="number">0</span>,</div><div class="line">                            bitmap.getWidth(), bitmap.getHeight(), matrix, <span class="keyword">true</span>);</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125; <span class="keyword">finally</span>&#123;</div><div class="line">            <span class="keyword">if</span>(fs!=<span class="keyword">null</span>) &#123;</div><div class="line">                <span class="keyword">try</span> &#123;</div><div class="line">                    fs.close();</div><div class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">                    e.printStackTrace();</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> bitmap;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     *</span></div><div class="line"><span class="comment">     * 读取图片属性：旋转的角度</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> path 图片绝对路径</span></div><div class="line"><span class="comment">     * <span class="doctag">@return</span> degree旋转的角度</span></div><div class="line"><span class="comment">     */</span></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">readPictureDegree</span><span class="params">(String path)</span> </span>&#123;</div><div class="line">        <span class="keyword">int</span> degree = <span class="number">0</span>;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            ExifInterface exifInterface = <span class="keyword">new</span> ExifInterface(path);</div><div class="line">            <span class="keyword">int</span> orientation = exifInterface.getAttributeInt(</div><div class="line">                    ExifInterface.TAG_ORIENTATION,</div><div class="line">                    ExifInterface.ORIENTATION_NORMAL);</div><div class="line">            <span class="keyword">switch</span> (orientation) &#123;</div><div class="line">                <span class="keyword">case</span> ExifInterface.ORIENTATION_ROTATE_90:</div><div class="line">                    degree = <span class="number">90</span>;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                <span class="keyword">case</span> ExifInterface.ORIENTATION_ROTATE_180:</div><div class="line">                    degree = <span class="number">180</span>;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                <span class="keyword">case</span> ExifInterface.ORIENTATION_ROTATE_270:</div><div class="line">                    degree = <span class="number">270</span>;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">            &#125;</div><div class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> degree;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 调用native方法</span></div><div class="line"><span class="comment">     * <span class="doctag">@Description</span>:函数描述</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> bit</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> quality</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> fileName</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> optimize</span></div><div class="line"><span class="comment">     * <span class="doctag">@author</span> XiaoSai</span></div><div class="line"><span class="comment">     * <span class="doctag">@date</span> 2016年3月23日 下午6:36:46</span></div><div class="line"><span class="comment">     * <span class="doctag">@version</span> V1.0.0</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">saveBitmap</span><span class="params">(Bitmap bit, <span class="keyword">int</span> quality, String fileName, <span class="keyword">boolean</span> optimize)</span> </span>&#123;</div><div class="line">        compressBitmap(bit, bit.getWidth(), bit.getHeight(), quality, fileName.getBytes(), optimize);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 调用底层 bitherlibjni.c中的方法</span></div><div class="line"><span class="comment">     * <span class="doctag">@Description</span>:函数描述</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> bit</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> w</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> h</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> quality</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> fileNameBytes</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> optimize</span></div><div class="line"><span class="comment">     * <span class="doctag">@return</span></span></div><div class="line"><span class="comment">     * <span class="doctag">@author</span> XiaoSai</span></div><div class="line"><span class="comment">     * <span class="doctag">@date</span> 2016年3月23日 下午6:35:53</span></div><div class="line"><span class="comment">     * <span class="doctag">@version</span> V1.0.0</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">native</span> String <span class="title">compressBitmap</span><span class="params">(Bitmap bit, <span class="keyword">int</span> w, <span class="keyword">int</span> h, <span class="keyword">int</span> quality, <span class="keyword">byte</span>[] fileNameBytes,</span></span></div><div class="line"><span class="function"><span class="params">            <span class="keyword">boolean</span> optimize)</span></span>;</div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 加载lib下两个so文件</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="keyword">static</span> &#123;</div><div class="line">        System.loadLibrary(<span class="string">"jpegbither"</span>);</div><div class="line">        System.loadLibrary(<span class="string">"bitherjni"</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="ThumbnailUtils系统工具类的使用"><a href="#ThumbnailUtils系统工具类的使用" class="headerlink" title="ThumbnailUtils系统工具类的使用"></a>ThumbnailUtils系统工具类的使用</h3><blockquote>
<p>纯属为了增加篇幅，大家别介意哈，咳咳, 其实也是为了记录一下,以后用到可以直接过来看</p>
</blockquote>
<p>创建一张视频的缩略图。如果视频已损坏或者格式不支持可能返回null。<br><br>filePath：视频文件路径<br><br>kind：文件种类，可以是 MINI_KIND 或 MICRO_KIND<br></p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function">Bitmap <span class="title">createVideoThumbnail</span><span class="params">(String filePath, <span class="keyword">int</span> kind)</span></span></div></pre></td></tr></table></figure>
<p>创建所需尺寸居中缩放的位图。<br><br>source： 需要被创造缩略图的源位图对象<br><br>width：　生成目标的宽度<br><br>height： 生成目标的高度<br><br>options：在缩略图抽取时提供的选项<br></p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function">Bitmap <span class="title">extractThumbnail</span><span class="params">(Bitmap source, <span class="keyword">int</span> width, <span class="keyword">int</span> height, <span class="keyword">int</span> options)</span></span></div></pre></td></tr></table></figure>
<p>创建所需尺寸居中缩放的位图。<br><br>source： 需要被创造缩略图的源位图对象<br><br>width：　生成目标的宽度<br><br>height： 生成目标的高度<br></p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function">Bitmap <span class="title">extractThumbnail</span><span class="params">(Bitmap source, <span class="keyword">int</span> width, <span class="keyword">int</span> height)</span></span></div></pre></td></tr></table></figure>
<blockquote>
<p>最后当然要奉上源码了，源码中封装了参考网上的拍照和选取图片工具类，有问题可以指出，共同进步!</p>
</blockquote>
<p><a href="http://download.csdn.net/download/h7870181/9487990" target="_blank" rel="external">eclipse代码</a></p>
<blockquote>
<p><b>2016.11.08更新：</b><br>     很多朋友说在AndroidStudio里面编译有问题，就抽了个时间重新写了一个DEMO给大家参考，要注意的地方就是要在build.gradle里面添加下面代码，否则就会报找不到so文件的错误。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">sourceSets &#123; </div><div class="line">   main &#123;</div><div class="line">        jniLibs.srcDirs = [<span class="string">'libs'</span>]</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><a href="https://github.com/h7870181/LibjpegCompress" target="_blank" rel="external">AndroidStudio代码</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/08/14/2016-08-14-glide/" rel="prev" title="glide图片加载库学习">
                glide图片加载库学习 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="Soaic" />
          <p class="site-author-name" itemprop="name">Soaic</p>
           
              <p class="site-description motion-element" itemprop="description">Welcome!</p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#质量压缩"><span class="nav-number">1.</span> <span class="nav-text">质量压缩</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#尺寸压缩"><span class="nav-number">2.</span> <span class="nav-text">尺寸压缩</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JNI调用libjpeg库压缩"><span class="nav-number">3.</span> <span class="nav-text">JNI调用libjpeg库压缩</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#结合三种方式的终极压缩"><span class="nav-number">4.</span> <span class="nav-text">结合三种方式的终极压缩</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#NativeUtil类的源码"><span class="nav-number">5.</span> <span class="nav-text">NativeUtil类的源码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ThumbnailUtils系统工具类的使用"><span class="nav-number">6.</span> <span class="nav-text">ThumbnailUtils系统工具类的使用</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Soaic</span>
</div>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("nSNhFcJCeysT9vRXgfNvtbQF-gzGzoHsz", "aegQNi8pntiOE4R2z0e5B84D");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
